package com.powernode.domain;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.util.StringUtils;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;


/**
 * 系统用户
 * 单独创建一个认证的类
    */
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@TableName(value = "sys_user")
public class SysLoginUser implements Serializable, UserDetails {
    @TableId(value = "user_id", type = IdType.AUTO)
    private Long userId;

    /**
     * 用户名
     */
    @TableField(value = "username")
    private String username;

    /**
     * 密码
     */
    @TableField(value = "`password`")
    private String password;

    /**
     * 状态  0：禁用   1：正常
     */
    @TableField(value = "`status`")
    private Integer status;

    /**
     * 用户所在的商城Id
     * shopId我们这个商城是一个多租户的商城
     * 一套代码需要给很多商家使用
     * 使用一个字段来进行区分隔离
     *
     *
     */
    @TableField(value = "shop_id")
    private Long shopId;

    @TableField(exist = false)
    private List<String> auths;

    /**
     * 权限
     * @return
     */
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        ArrayList<SimpleGrantedAuthority> authorities  = new ArrayList<>();
        auths.forEach(auth -> {
            if (StringUtils.hasText(auth)){
                if (auth.contains(",")){
                    //按照,来分割
                    String[] realAuths = auth.split(",");
                    for (String realAuth : realAuths) {
                        authorities.add(new SimpleGrantedAuthority(realAuth));
                    }
                }else {
                    //没有 ,
                    authorities.add(new SimpleGrantedAuthority(auth));
                }
            }
        });
        return authorities;
    }

    /**
     * 获取用户名返回用户id
     * @return
     */
    public String getUsername(){
        return String.valueOf(this.userId);
    }

    public String getPassword(){
        return this.password;
    }


    @Override
    public boolean isAccountNonExpired() {
        return this.status == 1;
    }

    @Override
    public boolean isAccountNonLocked() {
        return this.status == 1;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return this.status == 1;
    }

    @Override
    public boolean isEnabled() {
        return this.status == 1;
    }
}
